<template>
  <el-container v-loading="model.loading" class="pb-5 bg-gray" style="padding: 0 80px;">
    <el-header class="bg-white w-100" style="height: 80px;">
      <div class="d-flex justify-content-between pt-4">
        <div>
          <!-- v-permission="[2, 3]" -->
          <el-button type="primary" @click="addUser">添加省级用户</el-button>
          <span class="text-muted ml-3">总计: {{ model.count }}个用户</span>
        </div>
        <div>
          <el-input
            placeholder="输入用户名/姓名查询"
            v-model="keywords"
            class="width-300"
            @keyup.native.enter="newSearch"
          >
            <el-button
              slot="append"
              type="primary"
              style="outline: none;"
              icon="el-icon-search"
              @click="newSearch"
            ></el-button>
          </el-input>
          <el-button type="primary" class="ml-3" @click="exportExcel"
            >导出Excel<i class="el-icon-download"></i
          ></el-button>
        </div>
      </div>
    </el-header>
    <el-main class="p-0 pt-2">
      <el-table :data="model.rows">
        <el-table-column label="序号" min-width="25" align="center">
          <template slot-scope="scope">
            {{ scope.$index + 1 + model.pageSize * (model.pageIndex - 1) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="account"
          label="省级用户账号"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="name"
          label="姓名"
          align="center"
        ></el-table-column>
        <el-table-column prop="name" label="用户类型" align="center">
          <template slot-scope="scope">
            {{
              scope.row.apptype == 1
                ? "超级管理员"
                : scope.row.apptype == 2
                ? "统计分析员"
                : scope.row.apptype == 3
                ? "业务管理员"
                : ""
            }}
          </template>
        </el-table-column>
        <el-table-column
          prop="remark"
          style="max-width: 80px;"
          label="备注"
          align="center"
        >
          <template slot-scope="scope">
            {{
              scope.row.remark && scope.row.remark.length > 15
                ? scope.row.remark.substring(0, 15) + "..."
                : scope.row.remark
            }}
          </template>
        </el-table-column>
        <el-table-column prop="name" label="添加时间" align="center">
          <template slot-scope="scope">
            {{ $formatDateTime(scope.row.createdDate) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-tooltip content="重置密码" placement="top">
              <svg-icon
                @click="restPs(scope.row)"
                icon-class="reset-password"
                style="font-size: 1.2rem;"
              ></svg-icon>
            </el-tooltip>
            <el-tooltip content="重新编辑" placement="top">
              <i
                class="el-icon-edit ml-3"
                style="font-size: 1.2rem;"
                @click="reEdit(scope.row)"
              ></i>
            </el-tooltip>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="name" label="状态" align="center">
            <template slot-scope="scope">
              <el-tooltip
                :content="scope.row.status === 0 ? '启用' : '禁用'"
                placement="top"
              >
                <el-switch
                  @change="changeStatus(scope.row)"
                  :activeValue="1"
                  :inactiveValue="0"
                  v-model="scope.row.status"
                  active-color="#94C05A"
                  inactive-color="#aaa"
                >
                </el-switch>
              </el-tooltip>
            </template>
          </el-table-column> -->
      </el-table>
    </el-main>
    <el-pagination
      v-show="model.rows.length > 0"
      class="text-right py-3 pr-5 bg-white"
      @size-change="handleSizeChange"
      @current-change="val => this.model.pageLoad(val)"
      :current-page.sync="model.pageIndex"
      :page-sizes="[20, 50, 100, 200]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="model.count"
      :pager-count="7"
    >
    </el-pagination>
    <el-dialog
      :title="Boolean(ruleForm.id)? '修改省级用户' : '添加省级用户'"
      :close-on-click-modal="false"
      :visible.sync="outerVisible"
      @closed="clearRuleForm"
      width="700px"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="150px"
        style="width: 600px;"
      >
        <el-form-item label="省级用户账号" prop="account">
          <el-input
            v-model="ruleForm.account"
            placeholder="6-16位"
            :disabled="Boolean(ruleForm.id)"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户类型" prop="appType">
          <el-select
            :disabled="Boolean(ruleForm.id)"
            v-model="ruleForm.appType"
            placeholder="请选择用户类型"
            style="width: 450px;"
          >
            <el-option label="超级管理员" value="1"></el-option>
            <el-option label="统计分析员" value="2"></el-option>
            <el-option label="业务管理员" value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!ruleForm.id">
          <el-input
            type="password"
            v-model="ruleForm.password"
            placeholder="6-16位，必须由字母(区分大小写)和数字组成"
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            type="textarea"
            v-model="ruleForm.remark"
            :autosize="{ minRows: 4, maxRows: 6 }"
            placeholder="请输入备注，最长100汉字"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            class="width-100"
            @click="submitForm('ruleForm')"
            >提交</el-button
          >
          <el-button @click="outerVisible = false" class="width-100"
            >取消</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>
  </el-container>
</template>
<script>
import PagedList from "../../libs/PagedList";
import axios from "axios";
// 自定义密码验证
const validatePass = (rule, value, callback) => {
  if (value.length < 6 || value.length > 16) {
    callback(new Error("密码长度在 6 到 16 个字符"));
  } else if (!/^[a-zA-Z0-9_]{6,16}$/.test(value)) {
    callback(new Error("6-16位，必须由字母(区分大小写)和数字组成"));
  } else {
    callback();
  }
};

export default {
  name: "adminuser",
  title: "省级用户",
  data() {
    return {
      model: new PagedList("survey/user/getUser", 20, { type: 1 }),
      keywords: "",
      outerVisible: false,
      ruleForm: {
        account: "",
        appType: "1",
        areaId: null,
        cityId: null,
        name: "",
        password: "",
        region: [],
        remark: "",
        type: 1
      },
      rules: {
        account: [
          { required: true, message: "请输入省级用户账号", trigger: "blur" },
          { min: 6, max: 16, message: "长度在 6 到 16 个字符", trigger: "blur" }
        ],
        appType: [
          { required: true, message: "请选择用户类型", trigger: "change" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { validator: validatePass, trigger: "blur" }
        ],
        remark: [{ max: 100, message: "不超过100个字符", trigger: "blur" }]
      }
    };
  },
  mounted() {
    this.newSearch();
  },
  methods: {
    newSearch() {
      this.model.search({ mix: this.keywords });
    },
    handleSizeChange (pageSize ) {
      this.model.pageSize = pageSize
      this.newSearch();
    },
    addUser() {
      this.outerVisible = true;
    },
    exportExcel() {
      this.$exportExcel(
        `survey/excel/admin?mix=${this.keywords}&oauth=${
          this.$store.state.user.user.oauth
        }`
      );
    },
    restPs(user) {
      this.$confirm(`确认重置 ${user.name} 的密码为a123456 ?`, "确认重置密码", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.model.loading = true;
          axios
            .get(
              `survey/user/resetPwd?account=${encodeURIComponent(user.account)}`
            )
            .then(res => {
              if (res.data.code === "200") {
                this.$message({
                  type: "success",
                  message: "密码重置成功!"
                });
              } else {
                this.$codeError(res);
              }
            })
            .catch(error => {
              this.$catchError(error);
            })
            .finally(() => {
              this.model.loading = false;
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消重置"
          });
        });
    },
    reEdit(row) {
      this.ruleForm = Object.assign({}, row)
      this.$nextTick(() => {
        this.outerVisible = true;
      });
    },
    // 启用禁用(禁用功能暂时取消)
    changeStatus(user) {
      axios
        .get(
          `survey/user/updateStatus?id=${user.id}&status=${user.status}`,
          this.$paramsConvert()
        )
        .then(res => {
          if (res.data.code === "200") {
            this.$message({
              type: "success",
              message: "状态修改成功!"
            });
          } else {
            this.$codeError(res);
          }
        })
        .catch(error => {
          this.$catchError(error);
        });
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let url = "survey/user/addUser";
          if (this.ruleForm.id) {
            url = "survey/user/update";
          }
          axios
            .post(url, this.ruleForm)
            .then(res => {
              if (res.data.code === "200") {
                this.$message({
                  type: "success",
                  message: "添加成功!"
                });
                this.outerVisible = false;
                this.newSearch();
              } else {
                this.$codeError(res);
              }
            })
            .catch(error => {
              this.$catchError(error);
            });
        } else {
          return false;
        }
      });
    },
    clearRuleForm() {
      this.ruleForm = {
        account: "",
        appType: "1",
        areaId: null,
        cityId: null,
        name: "",
        password: "",
        region: [],
        remark: "",
        type: 1
      };
      // 重置验证器
      this.resetForm();
    },
    resetForm() {
      this.$refs["ruleForm"].resetFields();
    }
  }
};
</script>
